package com.boil.qz.safekavass.listener;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boil.pojo.ResultVo;
import com.boil.util.Constants;
import com.boil.util.SpringUtils;
import com.boil.qz.safekavass.websocket.WebSocketTextServer;

/**
 * 
 * Session 监听器。
 * 
 * @author ChenYong
 * @date 2016-11-29
 *
 */
public class SessionListener implements HttpSessionListener {
	/** 日志 */
	private static Logger log = LoggerFactory.getLogger(SessionListener.class);
	
	/**
	 * 
	 * Session 创建时执行。
	 * 
	 */
	@Override
	public void sessionCreated(HttpSessionEvent event) {
		try {
			HttpSession session = event.getSession();
			
			log.debug("监听 Session：{}--->创建", session.getId());
		} catch (Exception e) {
			log.error("监听 Session--->创建时出现异常，异常信息如下：{}", e);
		}
	}

	/**
	 * 
	 * Session 销毁时执行。
	 * 
	 */
	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		try {
			HttpSession session = event.getSession();
			
			log.debug("Session：{}--->销毁", session.getId());
			
			// 移除
			boolean removeFlag = Constants.ONLINE_SESSION_ID_LIST.remove(session.getId());
			
			// 移除成功
			if (removeFlag) {
				// 获取 WebSocket 文本服务器
				WebSocketTextServer webSocketTextServer = SpringUtils.getBean(Constants.WEB_SOCKET_TEXT_SERVER, WebSocketTextServer.class);
				// 结果 Vo
				ResultVo onlineSessionCountResultVo = new ResultVo();
				
				onlineSessionCountResultVo.setResultCode(Constants.ONLINE_SESSION_COUNT);
				onlineSessionCountResultVo.setResultMsg(Constants.ONLINE_SESSION_COUNT_MSG);
				onlineSessionCountResultVo.setResult(Constants.ONLINE_SESSION_ID_LIST.size());
				
				// 告诉所有客户端，有人退出啦
				webSocketTextServer.sendMessage(onlineSessionCountResultVo);
			}
		} catch (Exception e) {
			log.error("监听 Session--->销毁时出现异常，异常信息如下：{}", e);
		}
	}
}